package com.superafroman.utils.scanner.locater;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Implementation of {@link IClassLocater} that looks up classes on the class
 * path.
 */
public class ClasspathClassLocater implements IClassLocater {

    private Log log = LogFactory.getLog(getClass());

    public ClasspathClassLocater() {
    }

    /**
     * @return
     *         A {@link List} of {@link URI}s that point to each location or jar
     *         file on the class path.
     */
    public List<URI> getClassLocations() {

        String surefireClassPath = System.getProperty("surefire.test.class.path");
        String classPath = System.getProperty("java.class.path");
        String pathSeparator = System.getProperty("path.separator");

        if (StringUtils.isNotBlank(surefireClassPath)) {
            classPath += pathSeparator + surefireClassPath;
        }

        String[] classPathElements = classPath.split(pathSeparator);

        List<URI> locations = new ArrayList<URI>();

        for (String path : classPathElements) {
            try {
                locations.add(URI.create("file:///" + URIUtil.encodeAll(path)));
            } catch (URIException e) {
                log.warn("Classpath element not added to class locations.", e);
            }
        }

        return locations;
    }
}
